<template>
  <view class="uni-pa-4 bg-white">
    <view class="uni-pa-4">
      <uni-file-picker v-model="imageValue" @select="select" @delete="deleteImg" limit="9"
        title="最多選擇9張圖片"></uni-file-picker>
    </view>
    <input class="uni-py-4" type="text" v-model="body.title" placeholder="填寫標題會有更多贊哦~">
    <textarea class="uni-py-4" v-model="body.content" placeholder="添加正文" auto-height />
    <view>
      <text v-for="(item, index) in body.topic" :key="index" class="uni-px-2 text-blue-900">#{{ item }}</text>
    </view>
    <view class="uni-mt-16 uni-mb-8">
      <button class="uni-mr-4" @click="openPopup" type="default" size="mini"># 話題</button>
      <button type="default" size="mini">@ 用戶</button>
    </view>
    <uni-goods-nav @click="onClick" @buttonClick="toRelease" :fill="true" :options="options"
      :button-group="customButtonGroup" />
    <!-- 普通弹窗 -->
    <uni-popup ref="popup" type="bottom">
      <view class="bg-white">
        <uni-section title="輸入話題" subTitle="" type="line" padding>
          <uni-easyinput confirm v-model="topicValue" focus placeholder="請輸入内容" @confirm="pushTopic"></uni-easyinput>
        </uni-section>
        <uni-group>
          <view @click="selectTopic(item.name)" v-for="item in topic" :key="item.id"
            class="flex justify-between text-gray-500 uni-my-2">
            <text>#{{ item.name }}</text>
            <text>{{ item.browse }}次瀏覽</text>
          </view>
        </uni-group>
      </view>
    </uni-popup>
  </view>
</template>
  
<script>
import {
  httpNoteRelease,
  httpNoteDetail
} from '@/utils/api.js'
import { baseURL } from '@/utils/base.js'
export default {
  data() {
    return {
      body: {
        userId: '',
        title: '',
        content: '',
        carousel: [],
        topic: [],
      },
      imageValue: [],
      topicValue: '',
      options: [{
        icon: 'refreshempty',
        text: '保存'
      },
      {
        icon: 'trash',
        text: '刪除'
      }],
      customButtonGroup: [{
        text: '發表筆記',
        backgroundColor: '#e30e33',
        color: '#fff '
      }],
      topic: []
    }
  },
  onLoad() {
    uni.getStorage({
      key: 'draft_key',
      success: async (res) => {
        this.body = res.data
        this.body.carousel = JSON.parse(this.body.carousel)
        this.body.topic = JSON.parse(this.body.topic)
        // 展示图片，需要添加url键
        let imgs = []
        this.body.carousel.forEach(element => {
          imgs.push({ url: element })
        })
        this.imageValue = [...this.imageValue, ...imgs]
      }
    })
  },
  onHide() {
    this.body = {
      userId: '',
      title: '',
      content: '',
      carousel: [],
      topic: [],
    }
    this.imageValue = []
  },
  methods: {
    // 选择话题
    selectTopic(e) {
      this.$refs.popup.close()
      this.body.topic.push(e)
    },
    // 顶部点击
    onClick(e) {
      const index = e.index
      switch (index) {
        case 0:
          this.saveToDraft()
          break
        case 1:
          this.deleteDraft()
          break
      }
    },
    // 删除草稿
    deleteDraft() {
      uni.showModal({
        title: '確認刪除該草稿？',
        success: async (res) => {
          if (res.confirm) {
            uni.removeStorageSync('draft_key')
            uni.showToast({
              title: '刪除成功',
              icon: 'none'
            })
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }, 1000)
          }
        }
      })
    },
    // 保存草稿
    async saveToDraft() {
      const draft = {
        ...this.body,
        carousel: JSON.stringify(this.body.carousel),
        topic: JSON.stringify(this.body.topic)
      }
      // 存储到本地
      uni.setStorage({
        key: 'draft_key',
        data: draft,
        success: () => {
          uni.showToast({
            title: '保存成功',
            duration: 2000,
            complete: () => {
              // 清空内容
              this.content = ''
              this.imgList = []
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index'
                })
              }, 1000)
            }
          })
        }
      })
    },
    // 弹出框
    openPopup(e) {
      this.$refs.popup.open('top')
    },
    // 输入话题
    pushTopic(e) {
      this.body.topic.push(e)
      this.topicValue = ''
      this.$refs.popup.close()
    },
    // 获取上传状态
    select(e) {
      const tempFilePaths = e.tempFilePaths //e是获取的图片源
      uni.uploadFile({
        url: baseURL+'/file/upload', //上传图片的后端接口
        filePath: tempFilePaths[0],
        name: 'file',
        success: res => {
          this.body.carousel.push(JSON.parse(res.data).data.url)
        }
      })
    },
    // 删除照片
    deleteImg(e) {
      this.body.carousel = this.body.carousel.filter(item => item != e.tempFilePath)
    },
    // 发布
    async toRelease() {
      const {
        code
      } = await httpNoteRelease({
        ...this.body,
        carousel: JSON.stringify(this.body.carousel),
        topic: JSON.stringify(this.body.topic),
      })
      if (code === 200) {
        uni.showToast({
          title: '發佈成功',
          duration: 2000,
          complete: () => {
            // 清空内容
            this.content = ''
            this.imgList = []
            uni.removeStorageSync('draft_key')
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }, 1000)
          }
        })
      }
    }
  }
}
</script>
  
<style lang="scss" scoped>
// 底部栏
::v-deep .uni-tab__cart-box {
  z-index: 0 !important;
}

::v-deep .file-picker__box-content {
  background: #fff !important;
}
</style>